package com.epam.customer;

import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.epam.bank.Currency;
import com.epam.properties_loader.PropertiesHelper;

public class CustomerGenerator implements Runnable {
	private long timeout;
	private Customer currentCustomer;
	Properties props = new PropertiesHelper().getProperties();
	private static Logger logger = Logger.getLogger(CustomerGenerator.class);
	private static Random rand = new Random();

	public CustomerGenerator() {
		this.timeout = Long.valueOf(props.getProperty("lineSleepTime"));
	}

	public void run() {
		ExecutorService exec = Executors.newCachedThreadPool();
		try {
			while (!Thread.interrupted()) {
				currentCustomer=new Customer(randomTime(),randomCurrency(),
						randomAmount());
				exec.execute(currentCustomer);
				TimeUnit.MILLISECONDS.sleep(timeout);
			}
		} catch (InterruptedException e) {
			logger.error("Customer Generator interrupted!");
		} finally {
			exec.shutdownNow();
		}
		logger.error("Customer Generator terminated!");
}

	private Currency randomCurrency() {
		switch (rand.nextInt(2)) {
		case 0:
			return Currency.EUR;
		case 1:
			return Currency.USD;
		}
		return null;
	}

	private int randomTime() {
		int minTime=Integer.valueOf(props.getProperty("MinServingTime"));
		return minTime + rand.nextInt(100);
	}

	private int randomAmount() {
		return (50 + rand.nextInt(200));
	}
}
